package it.blog.controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.wsaddressing.W3CEndpointReference;


import it.blog.stub.*;

public class AddUser extends HttpServlet{


	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {

		response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/signUp.jsp"));

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		User user = new User();
		HttpSession session =  request.getSession();
		String sessionId= session.getId();
		BlogPortal bp = new BlogPortalService().getPort(BlogPortal.class);

		session.setAttribute("addUserFail",false);
		session.removeAttribute("mess");
		user.setName(request.getParameter("name"));
		user.setSurname(request.getParameter("surname"));
		user.setEmail( request.getParameter("email"));
		if(Integer.parseInt(request.getParameter("gender"))==1)
			user.setGender(true);
		else
			user.setGender(false);

		String date = request.getParameter("dateOfBirth");
		StringTokenizer st = new StringTokenizer(date,"/");
		Calendar c = Calendar.getInstance();
		if(date!=""){
			int day = Integer.parseInt(st.nextToken());
			int month = Integer.parseInt(st.nextToken());
			int year = Integer.parseInt(st.nextToken());
		    c.set(year, month, day);
		}

		user.setSiteURL(request.getParameter("siteURL"));
		user.setImgURL("");
		user.setUsername(request.getParameter("username"));
		user.setPassword(request.getParameter("password"));
		user.setState(true);
		user.setRole(2);
		try{
			user.setDateOfBirth(toXMLGregorianCalendar(c));
		} catch (DatatypeConfigurationException e) {
			session.setAttribute("addUserFail",true);
			//Rimando alla pagina cancellando la richiesta corrente
			response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/signUp.jsp"));

		}
		if(bp.addUser(user,sessionId)){
			//Redirect alla pagina opportuna dopo aver inserito correttamente l'utente
			String username= bp.getUserSession(sessionId).getUsername();
			String password= bp.getUserSession(sessionId).getPassword();
			
			session.setAttribute("addUserFail",false);
			W3CEndpointReference ref=bp.createUserSession(username, password,sessionId);
			if(ref!=null) {
				session.setAttribute("ref", ref);
				session.setAttribute("loginFail",false);
				session.setAttribute("user",bp.getUserSession(sessionId));

				response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/PortalServlet"));
			}

		}else{
			System.out.println("sono nell'else");
			session.setAttribute("addUserFail",true);
			session.setAttribute("mess","Utente NON registrato");
			//Rimando alla pagina cancellando la richiesta corrente
			response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/PortalServlet"));
		}

	}

	private static XMLGregorianCalendar toXMLGregorianCalendar(Calendar c) throws DatatypeConfigurationException {
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTimeInMillis(c.getTimeInMillis());
		XMLGregorianCalendar xc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
		if(xc.getMonth()==1)
			xc.setMonth(12);
		else
			xc.setMonth(xc.getMonth()-1);
		
		return xc;
	}

}
